package com.zimu.sdk.client;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.zimu.common.model.entity.User;
import com.zimu.sdk.utils.EncryptUtil;
import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Data
@AllArgsConstructor
public class ApiClient {
    private String accessKey;
    private String secretKey;
    public String getUserByGet(String name){
        String res = HttpUtil.get("http://localhost:8080/name", Map.of("name",name));
        return res;
    }
    public String getNameByPostParams(String name){
        String res = HttpUtil.post("http://localhost:8080/name", Map.of("name",name));
        return res;
    }

    private Map<String, List<String>> geneHeader(String json){
        Map<String,List<String>> header = new HashMap<>();
        header.put("accessKey",List.of(accessKey));
        //如果是post，使用body中json+密钥加密,get使用密钥加密
        String encryptKey = EncryptUtil.encrypt(json + secretKey);
        header.put("signed",List.of( encryptKey ));
        //时间戳,不得超过5分钟
        header.put("time",List.of( String.valueOf(System.currentTimeMillis()) ));
        //随机数
        String nonce = String.valueOf(RandomUtil.randomInt(4));
        header.put("nonce", List.of(nonce) );
        return header;
    }
    public String getUserByPost(User user){
        String json = JSONUtil.toJsonStr(user);
        HttpResponse res = HttpUtil.createPost("http://localhost:8080/name/user")
                .header(geneHeader(json))
                .body(json)
                .execute();
        return res.body();
    }
}
